const doms = {
  audioEl: document.querySelector("audio"),
  ulEl: document.querySelector(".container .lrc-list"),
  containerEl: document.querySelector(".container"),
};

function parseLrc() {
  const rets = [];
  lrc.split("\n").forEach((line) => {
    const [time, words] = line.split("]");
    const timeStr = time.substring(1);

    const obj = {
      time: parseTime(timeStr),
      words,
    };
    rets.push(obj);
  });

  return rets;
}

function parseTime(timeStr) {
  const parts = timeStr.split(":");
  return +parts[0] * 60 + +parts[1];
}

const lrcData = parseLrc();

function findIndex() {
  const currentTime = doms.audioEl.currentTime;

  for (let i = 0; i < lrcData.length; i++) {
    const lrcItem = lrcData[i];
    if (currentTime < lrcItem.time) {
      return i - 1;
    }
  }

  // 找遍了都没找到(说明播放当最后一句)
  return lrcData.length - 1;
}

// 界面
function createLrcElement() {
  const frag = document.createDocumentFragment();
  for (const lrcItem of lrcData) {
    const liEl = document.createElement("li");
    liEl.textContent = lrcItem.words;
    frag.appendChild(liEl);
  }

  doms.ulEl.appendChild(frag);
}

createLrcElement();

const containerH = doms.containerEl.clientHeight;
const liH = doms.ulEl.children[0].clientHeight;
// 最大偏移量，建议写在外面，不让写在setOffset中，会导致重复reflow
const maxOffset = doms.ulEl.clientHeight - containerH;
function setOffset() {
  const index = findIndex();
  const offset = Math.min(Math.max(0, liH * index + liH / 2 - containerH / 2), maxOffset);
  doms.ulEl.style.transform = `translateY(-${offset}px)`;
  doms.ulEl.querySelector(".active")?.classList.remove("active");
  doms.ulEl.children?.[index]?.classList.add("active");
}

doms.audioEl.addEventListener("timeupdate", setOffset);
